/** 仓储档案 */

import React, {useEffect, useState} from 'react'
import {Button, Space, message} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {history, connect} from 'umi'
import {ArrowDownOutlined, PlusOutlined} from '@ant-design/icons'
import moment from 'moment'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import Permissions from '@/components/Permissions'
import CustomTable from '@/components/Table'
import {getParkingfeesettlementList} from '@/service/storage/parkingLot'
import {getAllParking} from '@/service/storage/archives'
import {downloadDocumentUrl} from '@/service/common/download'
import {claimTaskCandidate} from '@/service/common'

interface DataType {
	auditResult: number
	showAuditButton: any
	processInstanceId: any
	warehouseName: string | string[] | null
	startUpStatus: number
	id: string
	supplierCode: string
	supplierName: string
	serviceType: string
	contacts: string
	status: string
	date: string
}

const formItemLayout = {
	labelCol: {flex: '120px'},
	wrapperCol: {flex: '1'},
}

const settlement = (props: any) => {
	const [dataSourse, setDataSourse] = useState<any[]>([])
	const [searchData, setSearchData] = useState({})
	const [loading, setLoading] = useState(false)
	const [total, setTotal] = useState()
	const [warehouseData, setWarehouseData] = useState<any>([])
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})

	// 获取停车场费用结算列表
	const getData = () => {
		setLoading(true)
		getParkingfeesettlementList({
			...params,
			startMonth: moment().subtract(2, 'month').format('YYYY-MM'),
			endMonth: moment().format('YYYY-MM'),
			...searchData,
		})
			.then((res: any) => {
				if (res?.success) {
					setDataSourse(res?.data?.records)
					setTotal(res?.data?.total)
					setLoading(false)
				} else {
					setLoading(false)
				}
			})
			.catch((err) => {
				setDataSourse([])
				message.error(err)
				setLoading(false)
			})
	}
	useEffect(() => {
		/** 获取停车场列表 */
		getAllParking({warehouseType: 1})
			.then((res: any) => {
				setWarehouseData(res.data)
			})
			.catch(() => {
				setWarehouseData([])
			})
	}, [])

	useEffect(() => {
		getData()
	}, [params])

	/** 点击详情及编辑事件 */
	const onDetails = (type: string, record: DataType) => {
		const queryData: any = {
			id: record?.id,
			name: record?.warehouseName,
			processInstanceId: record?.processInstanceId,
		}
		history.push({
			pathname: `/storage/parkingLot/settlement/${type}`,
			query: queryData,
		})
	}
	/** 拾取任务 */
	const pickTask = (processInstanceId: string) => {
		claimTaskCandidate({
			reviewerId: props?.user?.userId,
			processInstanceId,
		})
	}
	const columns: ColumnsType<DataType> = [
		{
			title: '仓库',
			dataIndex: 'warehouseArchivesName',
			align: 'center',
			width: 100,
		},
		{
			title: '结算单号',
			dataIndex: 'settlementNo',
			align: 'center',
			width: 150,
		},
		{
			title: '结算月份',
			dataIndex: 'startMonth',
			align: 'center',
			width: 100,
		},
		{
			title: '状态',
			dataIndex: 'auditResult',
			align: 'center',
			width: 100,
			render: (text) => {
				if (text === 1) {
					return '待审核'
				}
				if (text === 2) {
					return '审核中'
				}
				if (text === 4) {
					return '审核通过'
				}
				return '审核驳回'
			},
		},
		{
			title: '费用',
			dataIndex: 'costType',
			align: 'center',
			width: 140,
			render: (text) => <>{text === '1' ? '按车位' : '按月固定租金'}</>,
		},
		{
			title: '系统计算金额',
			dataIndex: 'totalAmount',
			align: 'center',
			width: 120,
			render: (text) => text || '-',
		},
		{
			title: '应付金额',
			dataIndex: 'actualAmount',
			align: 'center',
			width: 100,
			render: (text) => text || '-',
		},
		{
			title: '创建时间',
			dataIndex: 'createTime',
			align: 'center',
			width: 160,
		},
		{
			title: '创建人',
			dataIndex: 'createPerson',
			align: 'center',
			width: 100,
		},
		{
			title: '审批通过时间',
			dataIndex: 'updateTime',
			align: 'center',
			width: 160,
			render: (text, record) => (record?.auditResult === 4 ? text : '-'),
		},
		{
			title: '审批人',
			dataIndex: 'auditUserName',
			align: 'center',
			width: 180,
			render: (text) => text || '-',
		},
		{
			title: '车型',
			dataIndex: 'carModel',
			align: 'center',
			width: 180,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 120,
			render: (text: any, record) => (
				<Space size={12}>
					<Permissions permissionID="amc_storage_parkingLot_settlement_view">
						<Button
							type="link"
							onClick={() => {
								onDetails('view', record)
							}}>
							详情
						</Button>
					</Permissions>
					{record?.auditResult === 1 || record?.auditResult === 3 ? (
						<Permissions permissionID="amc_storage_parkingLot_settlement_edit">
							<Button
								type="link"
								onClick={() => {
									onDetails('edit', record)
								}}>
								编辑
							</Button>
						</Permissions>
					) : (
						''
					)}
					{record?.showAuditButton ? (
						<Permissions permissionID="amc_storage_parkingLot_settlement_examine">
							<Button
								type="link"
								onClick={() => {
									pickTask(record?.processInstanceId)
									onDetails('examine', record)
								}}>
								审核
							</Button>
						</Permissions>
					) : (
						''
					)}
				</Space>
			),
		},
	]
	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '结算单号',
					name: 'settlementNo',
					key: 'settlementNo',
				},
				{
					type: 'select',
					key: 'auditResult',
					name: 'auditResult',
					label: '状态',
					keys: 'value',
					title: 'text',
					items: [
						{
							value: 1,
							text: '待审核',
						},
						{
							value: 2,
							text: '审核中',
						},
						{
							value: 4,
							text: '审核通过',
						},
						{
							value: 3,
							text: '审核驳回',
						},
					],
				},
				{
					type: 'select',
					key: 'warehouseArchivesId',
					name: 'warehouseArchivesId',
					label: '所属仓库',
					keys: 'id',
					title: 'warehouseName',
					items: warehouseData,
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'time',
					subtype: 'month',
					valueTime: moment().subtract(2, 'month'),
					allowClear: false,
					label: '结算月份（起）',
					name: 'startMonth',
					key: 'startMonth',
				},
				{
					type: 'time',
					subtype: 'month',
					valueTime: moment(),
					allowClear: false,
					label: '结算月份（止）',
					name: 'endMonth',
					key: 'endMonth',
				},
				{
					type: 'input',
					label: '创建人',
					name: 'createPerson',
					key: 'createPerson',
				},
			],
		},
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '审批人',
					name: 'auditUserName',
					key: 'auditUserName',
				},
				{},
				{},
			],
		},
	]
	const onFinish = (values: any) => {
		const searchDatas = {
			...values,
			startMonth: values?.startMonth
				? moment(values?.startMonth).format('YYYY-MM')
				: moment().subtract(2, 'month').format('YYYY-MM'),
			endMonth: values?.endMonth
				? moment(values?.endMonth).format('YYYY-MM')
				: moment().format('YYYY-MM'),
		}
		setSearchData(searchDatas)
		setParams({
			current: 1,
			size: 10,
		})
	}

	const onReset = () => {
		setSearchData({})
		setParams({
			current: 1,
			size: 10,
		})
	}

	return (
		<div className={styles.settlement}>
			<div className={styles.content}>
				<div className={styles.search}>
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formItems}
						formLayout={formItemLayout}
					/>
				</div>
				<div className={styles.btnlist}>
					<Space size={12}>
						<Permissions permissionID="amc_storage_parkingLot_settlement_add">
							<Button
								icon={<PlusOutlined />}
								type="primary"
								ghost
								size="small"
								onClick={() => {
									history.push(
										'/storage/parkingLot/settlement/add',
									)
								}}>
								新增数据
							</Button>
						</Permissions>
						<Permissions permissionID="amc_storage_parkingLot_settlement_export">
							<Button
								icon={<ArrowDownOutlined />}
								className={styles.import}
								ghost
								size="small"
								onClick={() => {
									downloadDocumentUrl({
										resourceId: '137',
										queryDesc:
											'停车场费用结算导出,resourceId:137',
										queryParam: {
											startMonth: moment()
												.subtract(2, 'month')
												.format('YYYY-MM'),
											endMonth:
												moment().format('YYYY-MM'),
											...searchData,
										},
									})
								}}>
								导出
							</Button>
						</Permissions>
					</Space>
				</div>
				<CustomTable
					params={params}
					columns={columns}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataSourse}
				/>
			</div>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(settlement)
